<template>
  <div class="kpi">
    <van-sticky>
      <van-nav-bar title="选择指标" left-text="返回" left-arrow @click-left="returnBtn">
        <template #right>
          <!-- <van-icon name="search" size="22" /> -->
          <!-- <van-button type="primary" size="mini"  class="btns-a">确认选择</van-button> -->
        </template>
      </van-nav-bar>
    </van-sticky>
    <div class="kpi-list-content">
      <van-pull-refresh v-model="refreshing" @refresh="onRefresh">
        <van-list
          v-model:loading="loading"
          :finished="finished"
          finished-text="没有更多了"
          error-text="请求失败，点击重新加载"
          @load="getList"
          :offset='0'
        >
          <div class="list">
            <van-empty image="search" description="暂无数据" v-if="list.length === 0" />
            <ul v-else>
              <li v-for="(item,index) in list" :key="item.id" @click="handleCurrentChange(item, index)" :class="{'active': oIndex === index}">
                <div class="list-left">
                  <div class="list-text"><span>{{ item.kpiName }}</span></div>
                  <span class="list-amount">¥{{ item.amount }}</span>
                </div>
                <div class="list-m">
                  <DictTag :dict-list="getDictList('ExpenditureKpiPayType')" :dict-key="item.payType" />
                  <!--指标单来源--> 
                  <DictTag :dict-list="getDictList('ExpenditureKpiSource')" :dict-key="item.source" />
                </div>
         
                <div class="list-btn">
                  <EnumTag :enumList="getEnumList('ExpenditureKpiState')" :enumKey="item.state" />
                  <van-button type="default" plain size="mini" style="margin: 0 0.7rem" @click.self="kpiDetailsBtn(item)">查看详情</van-button>
                </div>
                <van-icon name="success" class="active-ico" v-if="oIndex === index" />
              </li>
            </ul>
          </div>
        </van-list>
      </van-pull-refresh>
      <div class="btns">
        <van-button icon="certificate" type="primary" class="btns-a" round  @click="onSureBtn" color="#4fa2f7" :disabled=" !(typeof(oIndex) === 'number') ">确认选择</van-button>
      </div>
    </div>
    <van-popup v-model:show="isShowModel" :closeable="true" :style="{ height: '80%', width: '90%' }">
      <div class="model">
        <div class="model-head">指标单详情</div>
        <div class="model-content">
          <div class="content">
            <span>预算年度：</span>
            <span>{{ expenditureKpiObj.year }}</span>
          </div>
          <div class="content">
            <span>支出类型：</span>
            <span>
              <DictTag :dict-list="getDictList('ExpenditureKpiPayType')" :dict-key="expenditureKpiObj.payType" />
            </span>
          </div>
          <div class="content">
            <span>经费类型：</span>
            <span>
              <DictTag :dict-list="getDictList('ExpenditureKpiFundType')" :dict-key="expenditureKpiObj.fundType" />
            </span>
          </div>
          <div class="content">
            <span>预算总金额：</span>
            <span>￥{{ expenditureKpiObj.amount }}</span>
          </div>
          <div class="content">
            <span>可用金额：</span>
            <span>￥{{ expenditureKpiObj.availableAmount }}</span>
          </div>
          <div class="content">
            <span>项目负责人部门：</span>
            <span>{{ showIdLabel(organizationList, expenditureKpiObj.organizationId, 'organizationName') }}</span>
          </div>
          <div class="content">
            <span>项目负责人：</span>
            <span>{{ showIdLabel(userList, expenditureKpiObj.managerId, 'name') }}</span>
          </div>
          <div class="content">
            <span>功能分类：</span>
            <span>{{ showIdLabel(expenditureFunctionalList, expenditureKpiObj.expenditureFunctionalId, 'name') }}</span>
          </div>
          <div class="content">
            <span>财政项目：</span>
            <span>{{ showIdLabel(expenditureFiscalList, expenditureKpiObj.expenditureFiscalId, 'name') }}</span>
          </div>
          <div class="content">
            <span>指标来源：</span>
            <span>
              <DictTag :dict-list="getDictList('ExpenditureKpiSource')" :dict-key="expenditureKpiObj.source" />
            </span>
          </div>
          <div class="content">
            <span>项目类型：</span>
            <span>{{ showIdLabel(expenditurePtypeList, expenditureKpiObj.expenditurePtypeId, 'name') }}</span>
          </div>
          <div class="content">
            <span>指标单状态：</span>
            <span>
              <EnumTag :enum-list="getEnumList('ExpenditureKpiState')" :enum-key="expenditureKpiObj.state" />
            </span>
          </div>
          <div class="content">
            <span>按经济分类控制金额：</span>
            <span>
              <EnumTag :enum-list="getEnumList('CommonYesNo')" :enum-key="expenditureKpiObj.isEconomic" />
            </span>
          </div>
        </div>
      </div>
    </van-popup>
  </div>
  
</template>
<script setup>
import { ref, watch } from 'vue'
import {doGet} from "@/config/http";
import {
  svc,
  showDictKeyLabel,
  showEnumKeyLabel,
  getDictList,
  getEnumList,
  alertErrorMsg,
  showIdLabel, 
  getListPageSize
} from "@/config/common";
import useUserStore from "@/store/modules/user";
import {getUserId} from "@/config/cookie";
import initListStore from '@/store/modules/initList'

const props = defineProps({
  itemsVisible: {
    required: true,
    type: Boolean,
  },
  state: {
    required: false,
    type: String,
  },
  expenditureKpiId: {
    required: false,
    type: String,
  },
})

let tableRadio = ref('')
let list = ref([])
let loading = ref(false)
let finished = ref(false)
let refreshing = ref(false)
let isShowModel = ref(false)
let expenditureKpiObj = ref(null)
let oIndex = ref(null)

let listQuery = ref({
  pageNum: 0,
  pageSize: 6,
  sortField: 'id',
  sortType: 'desc',
  kpiCode: null,
  kpiName: null,
  kpiDateStart: null,
  kpiDateEnd: null,
  year: null,
  payType: null,
  fundType: null,
  amount: null,
  organizationId: useUserStore().organization.organizationType !== '1' ? useUserStore().organization.id : '',
  managerId: useUserStore().organization.organizationType !== '1' ? getUserId() : '',
  expenditurePtypeId: null,
  expenditureFunctionalId: null,
  expenditureFiscalId: null,
  source: null,
  state: '2',
  createTimeStart: null,
  createTimeEnd: null,
  updateTimeStart: null,
  updateTimeEnd: null,
  totalAdjustmentAmount: 0, // 总调整金额
  totalQuotaAmount: 0, // 总下达金额
  totalApplicationAmount: 0, // 总申请金额
  totalReimbursementAmount: 0, // 总报账金额
  availableAmount: 0, // 可用金额
})
let radioRow = {}

let governmentList = initListStore().governmentList
let organizationList = initListStore().organizationList
let userList = initListStore().userList
let expenditurePtypeList = initListStore().expenditurePtypeList
let expenditureFunctionalList = initListStore().expenditureFunctionalList
let expenditureFiscalList = initListStore().expenditureFiscalList


const emit = defineEmits(['close', 'expenditureKpiSelect'])

// watch(() => [props.itemsVisible, props.expenditureKpiId], async vals => {
//   if (vals[0] === true) {
//     await getList()
//     if (vals[1]) {
//       tableRadio.value = vals[1]
//     }
//   }
// })

// async function initList() {
//   let p1 = doGet(svc, '/government/page', {pageSize: getListPageSize()}, false)
//   let p2 = doGet(svc, '/organization/page', {pageSize: getListPageSize()}, false)
//   let p3 = doGet(svc, '/user/page', {pageSize: getListPageSize()}, false)
//   let p4 = doGet(svc, '/expenditure-ptype/page', {pageSize: getListPageSize()}, false)
//   let p5 = doGet(svc, '/expenditure-functional/page', {pageSize: getListPageSize()}, false)
//   let p6 = doGet(svc, '/expenditure-fiscal/page', {pageSize: getListPageSize()}, false)
//   let resArray = await Promise.all([p1, p2, p3, p4, p5, p6])
//   governmentList.value = resArray[0]['records']
//   organizationList.value = resArray[1]['records']
//   userList.value = resArray[2]['records']
//   expenditurePtypeList.value = resArray[3]['records']
//   expenditureFunctionalList.value = resArray[4]['records']
//   expenditureFiscalList = resArray[5]['records']
// }

// 获取数据
async function getList() {
  // await initList()
  listQuery.value.pageNum++

  let res = await doGet(svc, '/customExpenditureKpis/queryExpenditureKpi', listQuery.value)

  if (refreshing.value) {
    list.value = [];
    refreshing.value = false;
  }

  if(list.value.length === 0) {
    list.value = res['records']
  } else {
    list.value = list.value.concat(res['records'])
  }
  
  loading.value = false
  
  if (list.value.length >= parseInt(res['total'])) {
    finished.value = true
    listQuery.value.pageNum = 0
  } else {
    finished.value = false
  }
  
}

// 选择
const handleCurrentChange = (val, index) =>{
  console.log('val=>',val);
  oIndex.value = index
  radioRow = val
}

const kpiDetailsBtn = (item) =>{
  expenditureKpiObj.value = item
  isShowModel.value = true
}

// 点确定
function onSureBtn() {
  if (!radioRow) {
    alertErrorMsg('请选择指标单')
    return
  }
  emit('expenditureKpiSelect', radioRow)
  emit('close')
}

function returnBtn() {
  emit('close')
}

const onRefresh = () => {
  // // 清空列表数据
  finished.value = false;
  listQuery.value.pageNum = 0
  list.value = []
  // 重新加载数据
  // 将 loading 设置为 true，表示处于加载状态
  loading.value = true;
  getList();
};

</script>
<style>
.list-m .el-tag {
  color: #000 !important;
}
</style>
<style scoped lang="scss">
.kpi {
    width: 100%;
    height: 100vh;
    background-color: #f5f2f2;
    position: absolute;
    left: 0;
    top: 0;
    right: 0;
    bottom: 0;
    overflow-y: auto;
}

.kpi-list-content {
  width: 100%;
  height: 100%;
}
.list-text {
  width: 70%;
  overflow: hidden; /* 确保超出容器的内容被裁剪 */
  white-space: nowrap; /* 确保文本在一行内显示 */
  text-overflow: ellipsis; /* 超出部分显示省略号 */
  // color: #1db0bf;
}
.list {
  width: 100%;
  height: calc( 100vh - 8rem);
  & ul {
    width: 100%;
    height: 100%;
    padding: 0 .625rem;
    scroll-behavior: smooth;
    overflow-y: auto;
    & li {
      border-bottom: 1px solid #C3C3C3;
      border-radius: 6px;
      margin: .625rem 0;
      background: #fff;
      padding: .625rem;
      box-shadow:0 0 5px var(--van-gray-5);
      position: relative;
      .list-left {
        display: flex;
        justify-content: space-between;
        // margin-top: .625rem;
       
      }
      .list-m {
        display: flex;
        align-items: center;
        // justify-content: space-between;
        flex-wrap: wrap;
        margin-top: .625rem;
        & span {
          color: 000;
          font-size: .875rem;
          border: 1px solid #000;
          padding: 0.1rem .5rem;
          display: inline-block;
          margin: 0 .3125rem;
          border-radius: 2px;
        }
      }
      .list-btn {
        display: flex;
        justify-content: flex-end;
        margin-top: .625rem;
      }
      & span {
        // color: #95d475;
        font-size: .875rem;
        font-weight: bold;
        // color: #000;
      }
    }
    & li.active {
      background: #fff1f1;
      box-shadow:0 0 5px #9b0f65;
    }
    .active-ico {
      position: absolute;
      left: 0;
      bottom: 0;
      background: #dfc059;
      color: #fff;
      border-radius: 50%;
    }
  }
}
.btns {
  width: 100%;
  // padding: 0 .625rem;
  overflow: hidden;
  position: fixed;
  bottom: 0.2rem;
  left: 0;
  display: flex;
  align-items: center;
  justify-content: center;
}
.list-amount {
  padding: .3rem 0.8rem;
  border-radius: 30px;
  color: #fff;
  background: #dfc059;
  
}
.model-head {
  font-size: 1.5rem;
  font-weight: bold;
  margin-top: 2rem;
  text-align: center;
}
.model-content {
  padding: 0 1.2rem;
}
.content {
  padding: .625rem 0;
  color: var(--van-gray-10);
  display: flex;
  // align-items: center;
}
.content span:nth-child(1) {
  display: inline-block;
  text-align: top;
  // width: 46%;
  min-width: 25%;
}
</style>

